// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.swing.JFrame;

import com.dustedpixels.jasmin.ui.VideoOutputCanvas;
import com.dustedpixels.jasmin.unit.Process;
import com.dustedpixels.jasmin.unit.Unit;
import com.dustedpixels.jasmin.unit.zx.ZXSpectrumPlus;
import com.dustedpixels.jasmin.unit.zx.ZXSpectrumPlusProcess;
import com.dustedpixels.jasmin.video.VideoOutput;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class Jasmin {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame("Name");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    
    VideoOutputCanvas videoOutputCanvas = new VideoOutputCanvas();
    frame.add(videoOutputCanvas);
    frame.pack();
    frame.setVisible(true);
    
    VideoOutput videoOutput = (VideoOutput) videoOutputCanvas;
    
    int[] videoRamArray = new int[1 << 14];
    
    InputStream input = new FileInputStream("DynamiteDan.scr");
    //InputStream input = new FileInputStream("ManicMiner.scr");
    System.out.println(input);
    try {
      for (int i = 0; i < 6912; i++) videoRamArray[i] = input.read();
    } finally {
      input.close();
    }

    int frameCycles = 3500000 * 4 / 50;
    boolean runAsProcess = false;
    
    if (!runAsProcess) {
      ZXSpectrumPlus zx = new ZXSpectrumPlus(videoOutput, videoRamArray);
      run(zx, frameCycles);
    } else {
      ZXSpectrumPlusProcess zx = new ZXSpectrumPlusProcess(videoOutput, videoRamArray);
      run(zx, frameCycles);
    }
  }
  
  public static void run(Unit unit, int frameCycles) throws Exception {
    long startMillis = System.currentTimeMillis();
    long cycles = frameCycles;
    while (true) {
      unit.updateEndPoints();

      if (cycles-- == 0) {
        long ms = System.currentTimeMillis() - startMillis;
        System.out.println("Frame complete in " + ms + "ms");
        Thread.sleep(Math.max(0, 20 - ms));
        startMillis = System.currentTimeMillis();
        cycles = frameCycles;
      }
    }
  }
  
  public static void run(Process process, int frameCycles) throws Exception {
    long startMillis = System.currentTimeMillis();
    while (true) {
      process.run(frameCycles);
      
      long ms = System.currentTimeMillis() - startMillis;
      System.out.println("Frame complete in " + ms + "ms");
      Thread.sleep(Math.max(0, 20 - ms));
      startMillis = System.currentTimeMillis();
    }
  }
}
